﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Globalization;

[assembly: CLSCompliant(false)]
namespace ULSLogExtractor
{
    class ULSLogExtractionList
    {
        internal enum JobStatus
        {
            InProgress,
            Completed,
            Failed,
            CompletedNoLog
        }

        private SPList _list;
        private SPList List
        {
            get
            {
                if (_list == null)
                {
                    string listUrl = SPUrlUtility.CombineUrl(ContextWeb.ServerRelativeUrl, "Lists/ULSLogExtractorList");
                    _list = ContextWeb.GetList(listUrl);
                }
                return _list;
            }
        }

        //private List<ULSLogExtractorListItem> _allItems;
        //public IEnumerable<ULSLogExtractorListItem> AllItems
        //{
        //    get
        //    {
        //        if (_allItems == null)
        //        {
        //            _allItems = new List<ULSLogExtractorListItem>();

        //            SPListItemCollection sharePointItems = this.List.Items;

        //            foreach (SPListItem sharePointItem in sharePointItems)
        //            {
        //                ULSLogExtractorListItem item = new ULSLogExtractorListItem(sharePointItem);

        //                _allItems.Add(item);
        //            }
        //        }
        //        return _allItems;
        //    }
        //}

        private List<ULSLogExtractorListItem> _notCompletedItems;
        public IEnumerable<ULSLogExtractorListItem> NotCompletedItems
        {
            get
            {
                if (_notCompletedItems == null)
                {
                    _notCompletedItems = new List<ULSLogExtractorListItem>();

                    SPQuery query = new SPQuery();
                    query.RowLimit = 5;
                    query.Query = "<Where><IsNull><FieldRef Name=\"JobStatus\" /></IsNull></Where>";

                    SPListItemCollection sharePointItems = this.List.GetItems(query);

                    foreach (SPListItem sharePointItem in sharePointItems)
                    {
                        ULSLogExtractorListItem item = new ULSLogExtractorListItem(sharePointItem);
                        _notCompletedItems.Add(item);
                    }
                }
                return _notCompletedItems;
            }
        }


        private SPWeb _contextWeb;
        private SPWeb ContextWeb
        {
            get
            {
                return _contextWeb;
            }
            set
            {
                _contextWeb = value;
            }
        }

        public ULSLogExtractionList(SPWeb contextWeb)
        {
            this.ContextWeb = contextWeb;
        }
    }

    class ULSLogExtractorListItem
    {
        public string CorrelationID
        {
            get
            {
                return this.GetFieldValue("CorrelationID");
            }
        }


        public string LogArea
        {
            get
            {
                return this.GetFieldValue("LogArea");
            }
        }

        public string LogCategory
        {
            get
            {
                return this.GetFieldValue("LogCategory");
            }
        }


        public string LogLevel
        {
            get
            {
                return this.GetFieldValue("LogLevel");
            }
        }


        //public string Title
        //{
        //    get
        //    {
        //        return this.GetFieldValue("Title");
        //    }
        //}

        public string TextToFind
        {
            get
            {
                return this.GetFieldValue("LogTextToFind");
            }
        }

        public string LogStartDate
        {
            get
            {
                return this.GetFieldValue("LogStartDate");
            }
        }

        public string LogEndDate
        {
            get
            {
                return this.GetFieldValue("LogEndDate");
            }
        }

        //internal ULSLogExtractionList.JobStatus JobStatus
        //{
        //    set
        //    {
        //        SetStatus(value);
        //    }
        //}

        //public string JobCompletion
        //{
        //    get
        //    {
        //        return this.GetFieldValue("JobCompletion");
        //    }
        //}

        private SPListItem _sharePointItem;
        private SPListItem SharePointItem
        {
            get
            {
                return _sharePointItem;
            }
        }

        public ULSLogExtractorListItem(SPListItem item)
        {
            item.Update();
            this._sharePointItem = item;
        }

        internal void SetStatus(ULSLogExtractionList.JobStatus jobStatus, string message)
        {
            string jobStatusFieldName = "JobStatus";
            uint lcid = Convert.ToUInt32(this.SharePointItem.Web.Locale.LCID);
            string resourceFileName = "ULSLogExtractorResources";

            switch (jobStatus)
            {
                case ULSLogExtractionList.JobStatus.InProgress:
                    this.SharePointItem[jobStatusFieldName] = SPUtility.GetLocalizedString("$Resources:Item_Status_InProgress", resourceFileName, lcid);
                    break;
                case ULSLogExtractionList.JobStatus.Completed:
                    this.SharePointItem[jobStatusFieldName] = SPUtility.GetLocalizedString("$Resources:Item_Status_Completed", resourceFileName, lcid);
                    break;
                case ULSLogExtractionList.JobStatus.Failed:
                    this.SharePointItem[jobStatusFieldName] =
                        string.Format(CultureInfo.CurrentCulture, "{0} : {1}", SPUtility.GetLocalizedString("$Resources:Item_Status_Failed", resourceFileName, lcid), message);
                    break;
                case ULSLogExtractionList.JobStatus.CompletedNoLog:
                    this.SharePointItem[jobStatusFieldName] = SPUtility.GetLocalizedString("$Resources:Item_Status_CompletedNoLog", resourceFileName, lcid);
                    break;
                default:
                    break;
            }

            this.SharePointItem.Update();
        }

        internal void SetStatus(ULSLogExtractionList.JobStatus jobStatus)
        {
            SetStatus(jobStatus, string.Empty);
        }

        public void AddAttachement(string logFilePath)
        {
            string fileName = System.IO.Path.GetFileName(logFilePath);
            System.IO.FileStream stream = System.IO.File.OpenRead(logFilePath);
            byte[] streamData = new byte[stream.Length];

            stream.Read(streamData, 0, System.Convert.ToInt32(stream.Length));
            stream.Close();

            this.SharePointItem.Attachments.Add(fileName, streamData);

            string attachement = this.SharePointItem.Attachments[0];

            SPFieldUrlValue urlValue = new SPFieldUrlValue();
            string listRootFolderUrl = this.SharePointItem.ParentList.RootFolder.ServerRelativeUrl;
            string itemID = this.SharePointItem.ID.ToString(CultureInfo.InvariantCulture);
            urlValue.Url = string.Format(CultureInfo.CurrentCulture, "{0}/Attachments/{1}/{2}", listRootFolderUrl, itemID, attachement);
            urlValue.Description = attachement;
            this.SharePointItem["LogAttachmentURL"] = urlValue;

            this.SharePointItem.Update();
        }


        private string GetFieldValue(string fieldName)
        {
            object fieldObject = this.SharePointItem[fieldName];
            string fieldValue = string.Empty;

            if (fieldObject != null)
            {
                fieldValue = fieldObject.ToString();
            }

            return fieldValue;
        }
    }
}
